package com.mall.order.biz.handler;

import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.shopping.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * step5
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {

    @Autowired
    private RedissonClient redissonClient;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        String cartKey = "cart:userId:" + createOrderContext.getUserId();

        // 清空购物车中已选中的商品
        RMap<String, CartProductDto> map = redissonClient.getMap(cartKey);

        if(map != null){

            map.entrySet().removeIf(entry -> ("true".equals(entry.getValue().getChecked())));
        }

        return true;
    }
}
